package cs543.library.rmi;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import org.json.JSONArray;
import org.json.JSONObject;


public class RmiServer implements Runnable {
	
	private final int PORT = 4242;
	
	private RmiServerRegistry registry = null;
	private ServerSocket server = null;

	public void run() {
		registry = new RmiServerRegistry ();
		try {
			server = new ServerSocket (PORT);
			
			while (true) {
				Socket socket = server.accept ();
				BufferedReader input = new BufferedReader (new InputStreamReader (
						socket.getInputStream ()));
				DataOutputStream output = new DataOutputStream (socket.getOutputStream ());
				
				JSONObject obj = new JSONObject (input.readLine ());

				String iface = obj.getString ("interface");
				RmiServerInterface clazz = registry.lookup (iface);

				String method = obj.getString ("method");
				JSONObject rep = new JSONObject ();
				rep.put ("interface", iface);
				rep.put ("method", method);
				JSONArray arr = null;
				if (clazz != null) {
					arr = clazz.call (method, obj.getJSONArray ("args"));
					rep.put ("values", arr);
				} else {
					arr = new JSONArray ();
					arr.put ("NOTFOUND");
					rep.put ("error", arr);
				}
				
				output.writeBytes (rep.toString () + "\n");
				socket.close ();
			}
		} catch (Exception e) {}
	}

}
